package com.pz.cloud.framework.util;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 *  远程调用工具类
 * @author 3hmzz
 */
public class RestUtil {

    public static RestUtil restUtil;
    private RestTemplate restTemplate;
    private RestTemplate balanceRestTemplate;
    static {
        get();
    }
    private RestUtil(){

    }
    public static <T>T execute(String url,MultiValueMap<String, String> body,MultiValueMap<String, String> head,Class<T> cls){
        HttpEntity httpEntity = assembleHttpEntity(body,head);
        T result =restUtil.restTemplate.exchange(url, HttpMethod.POST, httpEntity, cls).getBody();
        return result;
    }
    public static <T>T balanceExecute(String url,MultiValueMap<String, String> body,MultiValueMap<String, String> head,Class<T> cls){
        HttpEntity httpEntity = assembleHttpEntity(body,head);
        T result =restUtil.balanceRestTemplate.exchange(url, HttpMethod.POST, httpEntity, cls).getBody();
        return result;
    }
    private static HttpEntity assembleHttpEntity(MultiValueMap<String, String> body,MultiValueMap<String, String> head){
        if(head==null){
             head = new LinkedMultiValueMap<>();
        }
        /**
         * 传递请求头
         */
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while(headerNames.hasMoreElements()) {
                    String headerName = (String)headerNames.nextElement();
                    String headerValue = request.getHeader(headerName);
                    head.add(headerName, headerValue);
                }
            }
        }
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body,head);
        return httpEntity;
    }

    public static RestUtil get(){
        if(restUtil==null){
            restUtil = new RestUtil();
            restUtil.restTemplate = (RestTemplate) SpringContextUtils.getBean("restTemplate");
            restUtil.balanceRestTemplate = (RestTemplate) SpringContextUtils.getBean("balanceRestTemplate");
        }
        return restUtil;
    }
}
